<?php

namespace App\Http\Controllers\Admin;

use App\Clients\MeiTuan\AdminH5LoginConfig;
use App\Excels\Imports\RecordByHandleImporter;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AccountMapping;
use App\Models\Capital;
use App\Models\Mall;
use App\Models\MallDateFinance;
use App\Models\Project;
use App\Models\ProjectMall;
use App\Models\ProjectMallCapital;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class MallController extends Controller
{
    public function malls(){
        $malls = Mall::query()
            ->whereNotNull("sub_date")
            ->orderByDesc("id")
            ->get();
        return $this->httpSuccess($malls);
    }

    public function refreshMall(Request $request)
    {
        return $this->httpSuccess();
        try{
            $account = Account::query()->find(1);
            $client = new AdminH5LoginConfig($account);
            $queryData = [
                "pageNo"=>1,
                "pageSize"=>500,
                "yodaReady"=>"h5",
                "csecplatform"=>"4",
                "csecversion"=>"3.2.0",
            ];
            $response = $client->execute($queryData)->contents();
            $inserts = [];
            $insertMall = [];
            foreach ($response["merchants"] as $merchant){
                if($merchant["orgType"] == 5){
                    $inserts[] = [
                        "account_id"=>$account->id,
                        "merchant_no"=>$merchant["merchantNo"],
                        "mall_type"=>1,
                    ];
                    $insertMall[] = [
                        "merchant_no"=>$merchant["merchantNo"],
                        "name"=>$merchant["orgName"],
                        "poi_id"=>$merchant["poiId"],
                    ];

                }

                foreach ($merchant["pois"] as $mer){
                    $inserts[] = [
                        "account_id"=>$account->id,
                        "merchant_no"=>$mer["merchantNo"],
                        "mall_type"=>1,
                    ];
                    $insertMall[] = [
                        "merchant_no"=>$mer["merchantNo"],
                        "name"=>$mer["orgName"],
                        "poi_id"=>$mer["poiId"],
                    ];
                }
            }

            DB::beginTransaction();
            try{
                AccountMapping::query()->upsert($inserts,["merchant_no"],["account_id","mall_type"]);
                Mall::query()->upsert($insertMall,["merchant_no"],["name","poi_id"]);
                DB::commit();
            }catch (Exception $e){
                DB::rollBack();
                throw $e;
            }
            return $this->httpSuccess();
        }catch (Exception $e){
            return $this->httpError($e->getMessage());
        }
    }

    public function save(Request $request)
    {
        $id = $request->input("id","");
        $merchantNo = $request->input("merchantNo","");
        $projectId = $request->input("projectId","");
        $money = $request->input("money","");
        empty($money) and $money = 0;
        $incomeRate = $request->input("incomeRate","");
        empty($incomeRate) and $incomeRate = 0;
        $subAccountRate = $request->input("subAccountRate","");
        empty($subAccountRate) and $subAccountRate = 0;
        $contacter = $request->input("contacter","");
        empty($contacter) and $contacter = "";
        $phone = $request->input("phone","");
        empty($phone) and $phone = "";
        $addr = $request->input("addr","");
        empty($addr) and $addr = "";
        $email = $request->input("email","");
        empty($email) and $email = "";
        $businessLicenseImage = $request->input("businessLicenseImage","");
        $otherFileUrl = $request->input("otherFileUrl","");
        $capitalIds = $request->input("capitalIds","");
        $subDate = $request->input("subDate","");
        $showDate = $request->input("showDate","");
        empty($showDate) and $showDate = null;
        $endBackDate = $request->input("endBackDate","");
        empty($endBackDate) and $endBackDate = null;

        if(empty($id)){
            $model = new ProjectMall;
            $model->mall_no = "MX".date("YmdHis").rand(1000,9999);
        }else{
            $model = ProjectMall::query()->find($id);
        }
        DB::beginTransaction();
        try{
            $model->merchant_no = $merchantNo;
            $model->project_id = $projectId;
            $model->money = $money;
            $model->income_rate = $incomeRate;
            $model->sub_account_rate = $subAccountRate;
            $model->contacter = $contacter;
            $model->phone = $phone;
            $model->addr = $addr;
            $model->email = $email;
            $model->business_license_image = $businessLicenseImage;
            $model->other_file_url = $otherFileUrl;
            $model->show_date = $showDate;
            $model->end_back_date = $endBackDate;
//            var_dump($model);
//            exit();
            $model->save();
            ProjectMallCapital::query()->where("p_mall_id",$model->id)->delete();
            $inserts = [];
            $total = 0;
            foreach ($capitalIds as $capitalId){
                $total += $capitalId["money"];
                $inserts[] = [
                    "p_mall_id"=>$model->id,
                    "capital_id"=>$capitalId["capitalId"],
                    "rate"=>0,
                    "money"=>$capitalId["money"],
                ];
            }
            if($model->money != $total) throw new Exception("资方出资金额合计需要等于出资总额");

            $settleMoney = MallDateFinance::query()
                ->where("merchant_no",$model->merchant_no)
                ->sum("settle_money");
            if($settleMoney < $model->money){
                $model->incom_status = 0;
            }elseif ($settleMoney >= $model->money * (1 + $model->income_rate / 100)){
                $model->incom_status = 2;
            }else{
                $model->incom_status = 1;
            }
            $mall = Mall::query()->where("merchant_no",$model->merchant_no)->first();
            if(!empty($subDate)){
                $mall->sub_date = $subDate;
                $mall->save();
            }
            $model->save();
            !empty($inserts) and ProjectMallCapital::query()->insert($inserts);
            DB::commit();
            return $this->httpSuccess();
        }catch (Exception $e){
            DB::rollBack();
            return $this->httpError($e->getMessage());
        }
    }

    public function pageItems(Request $request)
    {
        $mallNo = $request->input("mallNo","");
        $merchantNo = $request->input("merchantNo","");
        $capitalId = $request->input("capitalId","");
        $moneyLeft = $request->input("moneyLeft","");
        $moneyRight = $request->input("moneyRight","");
        $incomeRateLeft = $request->input("incomeRateLeft","");
        $incomeRateRight = $request->input("incomeRateRight","");
        $subAccountRateLeft = $request->input("subAccountRateLeft","");
        $subAccountRateRight = $request->input("subAccountRateRight","");
        $createdAtLeft = $request->input("createdAtLeft","");
        $createdAtRight = $request->input("createdAtRight","");
        $page = $request->input("page",1);
        $pageSize = $request->input("pageSize",20);
        $paginate = ProjectMall::query()
            ->with([
                "project"=>function ($query){
                    return $query->select("id","name");
                },
                "mall"=>function ($query){
                    return $query->select("merchant_no","name","sub_date");
                },
                "capital"=>function ($query){
                    return $query->select("capital.id","capital.name");
                },
                "capitalRel.capital"
            ])
            ->from("project_mall as a")
            ->when($mallNo, function (Builder $query)use($mallNo) {
                $query->where("a.mall_no",$mallNo);
            })
            ->when($merchantNo, function (Builder $query)use($merchantNo) {
                $query->where("a.merchant_no",$merchantNo);
            })
            ->when($capitalId, function (Builder $query)use($capitalId) {
                $subQuery = ProjectMallCapital::query()
                    ->where("capital_id",$capitalId)
                    ->groupBy("p_mall_id")
                    ->select("p_mall_id");
                $query->joinSub($subQuery, 'b', function (JoinClause $join) {
                    $join->on('a.id', '=', 'b.p_mall_id');
                });
            })
            ->when($moneyLeft, function (Builder $query)use($moneyLeft) {
                $query->where("a.money",">=",$moneyLeft);
            })
            ->when($moneyRight, function (Builder $query)use($moneyRight) {
                $query->where("a.money","<=",$moneyRight);
            })
            ->when($incomeRateLeft, function (Builder $query)use($incomeRateLeft) {
                $query->where("a.income_rate",">=",$incomeRateLeft);
            })
            ->when($incomeRateRight, function (Builder $query)use($incomeRateRight) {
                $query->where("a.income_rate","<=",$incomeRateRight);
            })
            ->when($subAccountRateLeft, function (Builder $query)use($subAccountRateLeft) {
                $query->where("a.sub_account_rate",">=",$subAccountRateLeft);
            })
            ->when($subAccountRateRight, function (Builder $query)use($subAccountRateRight) {
                $query->where("a.sub_account_rate","<=",$subAccountRateRight);
            })
            ->when($createdAtLeft, function (Builder $query)use($createdAtLeft) {
                $query->where("a.created_at",">=",$createdAtLeft);
            })
            ->when($createdAtRight, function (Builder $query)use($createdAtRight) {
                $query->where("a.created_at","<=",$createdAtRight);
            })
            ->select("a.*")
            ->orderByDesc("a.id")
            ->paginate($pageSize,['*'],'page',$page);
        return $this->httpSuccess([
            "total"=>$paginate->total(),
            "items"=>$paginate->items(),
        ]);

    }

    public function updateStatus(Request $request){
        $status = $request->input("status");
        $ids = $request->input("ids",[]);
        ProjectMall::query()->whereIn("id",$ids)->update(["status"=>$status]);
        return $this->httpSuccess();
    }

    public function delete(Request $request){
        $ids = $request->input("ids",[]);
        ProjectMall::query()->whereIn("id",$ids)->delete();
        return $this->httpSuccess();
    }

    public function queryDiffRange(Request $request){
        $id = $request->input("id","");
        $timeLeft = $request->input("timeLeft","");
        $timeRight = $request->input("timeRight","");
        $pmall = ProjectMall::query()
            ->with([
                "mall"
            ])
            ->where("id",$id)
            ->first();
        $dateList = MallDateFinance::query()
            ->where("merchant_no",$pmall->merchant_no)
            ->where("date",">=",$timeLeft)
            ->where("date","<=",$timeRight)
            ->get();
        $subamount = $dateList->sum("settle_money");
        $income = $dateList->sum("income");
        $canamount = round($income * ($pmall->sub_account_rate / 100),2);
        if(abs($canamount - $subamount) <= 0.1){
            $subamount = $canamount;
        }
        $subamount = round($subamount,2);
        $diffamount = round($canamount - $subamount,2);
        return $this->httpSuccess([
            "income"=>$canamount,
            "subamount"=>$subamount,
            "diffamount"=>$diffamount,
            "mallInfo"=>$pmall
        ]);
    }

    public function diffRangeSave(Request $request){
        $id = $request->input("id","");
        $timeLeft = $request->input("timeLeft","");
        $timeRight = $request->input("timeRight","");
        $pmall = ProjectMall::query()
            ->with([
                "mall"
            ])
            ->where("id",$id)
            ->first();
        $dateList = MallDateFinance::query()
            ->where("merchant_no",$pmall->merchant_no)
            ->where("date",">=",$timeLeft)
            ->where("date","<=",$timeRight)
            ->get();
        foreach ($dateList as $dateData){
            $subamount = $dateData->settle_money;
            $income = $dateData->income;
            $canamount = $income * ($pmall->sub_account_rate / 100);
            $dateData->settle_money = $canamount;
            $dateData->is_update = 1;
            $dateData->save();
        }
        return $this->httpSuccess();
    }

    public function recordByHandle(Request $request){
        $fileUrl = $request->input("fileUrl","");
        $id = $request->input("id","");
        $importer = new RecordByHandleImporter;
        Excel::import($importer, public_path($fileUrl));
        if(empty($importer->datas)) return $this->httpSuccess();
        $mall = ProjectMall::query()->find($id);
        $inserts = [];
        foreach ($importer->datas as $data){
            $inserts[] = [
                "bill_no"=>$data["date"],
                "merchant_no"=>$mall->merchant_no,
                "date"=>$data["date"],
                "income"=>$data["income"],
                "settle_money"=>$data["settle_money"],
                "is_update"=>1,
            ];
        }
        MallDateFinance::query()->upsert($inserts,["merchant_no","date"],["income","settle_money","is_update"]);
        return $this->httpSuccess();
    }






}
